import React from 'react';
import { hashHistory } from 'react-router';
import { Breadcrumb, Form, Input, Icon, Select, Button, Upload, message } from 'antd';

import $ from 'jquery';
import Config from '../../common/config';


const FormItem = Form.Item;
const Option = Select.Option;
const config = new Config();
const token = sessionStorage.getItem('token');
class merchandiseList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: JSON.parse(sessionStorage.getItem('UserInfo')).userid, // 操作人用户ID
      fileList1: [], //上传的商品主图
      fileList5: [], //商品详情页用的5张图片
      operation: this.props.params.state, // 操作 add:新增 update:修改
      detail: {}, // 修改详情
    }
  }

  componentDidMount() {
    const operation = this.props.params.state
    if (operation === 'update') {
      const detail = this.props.location.state.data
      console.log(detail)
      const { fileList1, fileList5 } = this.state;
      fileList1.push({
        uid: -1,
        name: detail.qrCodeImg,
        status: 'done',
        url: config.Filepath + detail.qrCodeImg,
        thumbUrl: config.Filepath + detail.qrCodeImg,
      });
      // detail.detailImg.split(',').map((item, index) => {
      //   fileList5.push({
      //     uid: -(index + 1),
      //     name: item,
      //     status: 'done',
      //     url: config.Filepath + item,
      //     thumbUrl: config.Filepath + item,
      //   });
      // })
      this.props.form.setFieldsValue({
        weChatId: detail.weChatId,
        sortCode: detail.sortCode,
        qrCodeImg: fileList1
      })
      this.setState({
        detail,
        fileList1,
        // fileList5
      })
    }
    $('.rdw-image-wrapper .rdw-option-wrapper').click(
      (e) => {
        $('#xFile').trigger('click');
        $('.rdw-image-modal').focus();
      }
    );
  }


  //富文本编辑器图片上传
  upload(e) {
    const formData = new FormData(); //创建一个form表单对象
    formData.append('Filedata', e.target.files[0]); //表单对象压入图片
    if (e.target.files.length) {

      const xhr = new XMLHttpRequest();
      xhr.open('POST', config.UploadFile + '/websitProductImg');
      xhr.send(formData);
      xhr.addEventListener('load', () => {
        const response = JSON.parse(xhr.responseText);
        if (response.code == 200) {
          this.setState({
            imageFile: response.data
          }, () => {
            $('.rdw-image-modal-url-input')[0].value = config.Filepath + response.data;
            $('.rdw-image-modal-size .rdw-image-modal-size-input')[1].value = '100%';
            $('.rdw-image-modal-url-input').focus();
            $('.rdw-image-modal-url-input').blur();
          });
        }
      });
      xhr.addEventListener('error', () => {
        const error = JSON.parse(xhr.responseText);
      });
    }
  }

  //限制用户必须上传图片格式的文件、图片大小
  beforeUpload(file, fileList) {
    let isIMG = file.type.indexOf('image') != -1;
    if (!isIMG) {
      message.config({ top: 50 });
      message.error('您只能上传图片！');
    }
    let isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.config({ top: 50 });
      message.error('您上传的图片大小必须小于10MB！');
    }
    return isIMG && isLt10M;
  }

  //上传图片
  normFile1(e) {
    this.setState({
      fileList1: e.fileList
    });
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  //上传图片
  normFile5(e) {
    this.setState({
      fileList5: e.fileList
    });
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 新增或修改
  save(e) {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      console.log(values)
      if (!err) {
        let url = `${config.jusewebsite_zml}/counselor`
        const data = {
          // themeImg: values.themeImg[0].response ? values.themeImg[0].response.data : values.themeImg[0].name,
          // title: values.title,
          // describe: values.describe,
          // detailImg: values.detailImg.map(item => item.response ? item.response.data : item.name).join(',')
          qrCodeImg: values.qrCodeImg[0].response ? values.qrCodeImg[0].response.data : values.qrCodeImg[0].name,
          weChatId: values.weChatId,
          sortCode: values.sortCode,
        }
        if (this.state.operation === 'add') {
          url += '/add'
        } else {
          url += '/update'
          data.id = this.state.detail.id
        }
        $.ajax({
          url,
          type: 'post',
          data,
          headers: {
            'Authorization': 'Bearer ' + token,
          },
          success: res => {
            console.log('操作产品', res)
            if (res.code === 200) {
              message.success(res.mes)
              this.linkPrev()
            }
          }
        })
      }
    })
  }

  // 跳转上一个页面
  linkPrev() {
    if (this.state.operation === 'add') {
      hashHistory.push({ pathname: '/consultant_zml' })
    } else {
      const paths = {
        pathname: '/consultant_zml',
        //       state: this.props.location.state
      };
      hashHistory.push(paths);
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = { labelCol: { span: 3 }, wrapperCol: { span: 21 } };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 3,
        },
      },
    };

    return (
      <div className='contentBox clearfix'>
        <div className="member-content-Search">
          <div className='breadcrumb'>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>官网管理</Breadcrumb.Item>
              {
                this.state.operation === 'add'
                  ?
                  <Breadcrumb.Item>新增</Breadcrumb.Item>
                  :
                  <Breadcrumb.Item>修改</Breadcrumb.Item>
              }
            </Breadcrumb>
            <div className="ctoutd" style={{ width: '50%', marginTop: 50 }}>
              <Form onSubmit={this.save.bind(this)} >
                <FormItem
                  label="二维码图片"
                  {...formItemLayout}
                >
                  {getFieldDecorator('qrCodeImg', {
                    valuePropName: 'fileList1', getValueFromEvent: this.normFile1.bind(this),
                    rules: [{ required: true, message: '请上传案例图片！' }],
                  })(
                    <Upload
                      accept="image/*"
                      name="img"
                      action={config.UploadFile + "/websitProductImg"}
                      beforeUpload={this.beforeUpload.bind(this)}
                      listType="picture"
                      className="upload-list-inline onepicture"
                      defaultFileList={this.state.fileList1}
                    >
                      {
                        this.state.fileList1.length >= 1 ? null :
                          <Button><Icon type="upload" /> 上传图片</Button>
                      }
                    </Upload>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="微信号"
                  hasFeedback
                >
                  {getFieldDecorator('weChatId', {
                    rules: [{
                      required: true, message: '请填写案例标题!',
                    }, {
                      validator: this.checkConfirm,
                    }],
                  })(
                    <Input type="title" placeholder='请填写案例标题' />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="排列顺序"
                  hasFeedback
                >
                  {
                    getFieldDecorator('sortCode', {
                      rules: [
                        { required: true, message: '请选择排列顺序' },
                      ],
                    })(
                      <Select placeholder="请选择排列顺序" >
                        <Option value='3' >3</Option>
                        <Option value='2' >2</Option>
                        <Option value='1' >1</Option>
                      </Select>
                    )
                  }
                </FormItem>
                <FormItem {...tailFormItemLayout}>
                  <Button type="primary" htmlType="submit" size="small" style={{ width: '100px', height: '35px' }}>确定</Button> <Button style={{ width: '100px', height: '35px' }} htmlType="button" onClick={this.linkPrev.bind(this)} size="small">取消</Button>
                </FormItem>
              </Form>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Form.create()(merchandiseList);
